"""
考试系统 - API视图
"""
from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django_filters.rest_framework import DjangoFilterBackend
from django.db.models import Q, Count, Avg, Sum, F, Func, Value
from django.shortcuts import get_object_or_404
from django.utils import timezone
from django.http import HttpResponse
import json
import csv
import io

from .models import (
    Examination, ExaminationQuestion, ExaminationSession,
    ExaminationAnswer, ExaminationTemplate, ExamStatistics
)
from .serializers import (
    ExaminationSerializer, ExaminationDetailSerializer, ExaminationCreateSerializer,
    ExaminationListSerializer, ExaminationSessionSerializer, ExaminationSessionDetailSerializer,
    ExaminationAnswerSerializer, ExaminationAnswerCreateSerializer, SessionAnswerDetailSerializer,
    ExaminationTemplateSerializer, ExamStatisticsSerializer, QuestionBankSelectSerializer
)
from apps.question_bank.serializers import QuestionListSerializer


class ExaminationViewSet(viewsets.ModelViewSet):
    """考试ViewSet"""
    permission_classes = [IsAuthenticated]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['exam_type', 'status', 'question_bank']

    def get_queryset(self):
        """根据用户权限获取考试"""
        user = self.request.user

        if user.is_admin_user:
            return Examination.objects.all()
        elif user.is_teacher:
            # 教师可以查看自己创建的和监考的考试
            return Examination.objects.filter(
                Q(creator=user) | Q(supervisors=user)
            ).distinct()
        else:
            # 学生只能查看已发布的考试
            return Examination.objects.filter(status='published')

    def get_serializer_class(self):
        """根据操作类型获取序列化器"""
        if self.action == 'list':
            return ExaminationListSerializer
        elif self.action == 'create':
            return ExaminationCreateSerializer
        elif self.action == 'retrieve':
            return ExaminationDetailSerializer
        return ExaminationSerializer

    def perform_create(self, serializer):
        """创建考试时设置创建者"""
        serializer.save(creator=self.request.user)

    def get_permissions(self):
        """根据操作类型获取权限"""
        if self.action in ['create', 'update', 'partial_update', 'destroy']:
            # 考试管理需要教师或管理员权限
            from common.permissions import IsTeacherOrAdmin
            return [IsAuthenticated, IsTeacherOrAdmin]
        return super().get_permissions()

    @action(detail=True, methods=['post'])
    def publish(self, request, pk=None):
        """发布考试"""
        examination = self.get_object()

        # 权限检查
        if examination.creator != request.user and not request.user.is_admin_user:
            return Response(
                {'error': '没有权限操作此考试'},
                status=status.HTTP_403_FORBIDDEN
            )

        if examination.status != Examination.ExamStatus.DRAFT:
            return Response(
                {'error': '只有草稿状态的考试才能发布'},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 检查配置
        if not examination.questions.exists():
            return Response(
                {'error': '考试没有题目'},
                status=status.HTTP_400_BAD_REQUEST
            )

        examination.status = Examination.ExamStatus.PUBLISHED
        examination.save(update_fields=['status'])

        return Response({'success': True, 'message': '考试已发布'})

    @action(detail=True, methods=['post'])
    def start(self, request, pk=None):
        """开始考试"""
        examination = self.get_object()

        # 权限检查
        if examination.creator != request.user and not request.user.is_admin_user:
            return Response(
                {'error': '没有权限操作此考试'},
                status=status.HTTP_403_FORBIDDEN
            )

        if examination.status != Examination.ExamStatus.PUBLISHED:
            return Response(
                {'error': '只有已发布的考试才能开始'},
                status=status.HTTP_400_BAD_REQUEST
            )

        now = timezone.now()
        if now < examination.start_time:
            return Response(
                {'error': '考试尚未开始'},
                status=status.HTTP_400_BAD_REQUEST
            )

        examination.status = Examination.ExamStatus.ONGOING
        examination.save(update_fields=['status'])

        return Response({'success': True, 'message': '考试已开始'})

    @action(detail=True, methods=['post'])
    def end(self, request, pk=None):
        """结束考试"""
        examination = self.get_object()

        # 权限检查
        if examination.creator != request.user and not request.user.is_admin_user:
            return Response(
                {'error': '没有权限结束此考试'},
                status=status.HTTP_403_FORBIDDEN
            )

        if examination.status != Examination.ExamStatus.ONGOING:
            return Response(
                {'error': '只有进行中的考试才能结束'},
                status=status.HTTP_400_BAD_REQUEST
            )

        examination.status = Examination.ExamStatus.FINISHED
        examination.save(update_fields=['status'])

        # 强制提交所有进行中的考试会话
        ExaminationSession.objects.filter(
            examination=examination,
            status=ExaminationSession.SessionStatus.IN_PROGRESS
        ).update(
            status=ExaminationSession.SessionStatus.TIMEOUT,
            finished_at=timezone.now()
        )

        return Response({'success': True, 'message': '考试已结束'})

    @action(detail=True, methods=['get'])
    def participants(self, request, pk=None):
        """获取参与考试的用户"""
        examination = self.get_object()

        # 权限检查
        if (examination.creator != request.user and
            not request.user.is_admin_user and
            not examination.supervisors.filter(id=request.user.id).exists()):
            return Response(
                {'error': '没有权限查看参与信息'},
                status=status.HTTP_403_FORBIDDEN
            )

        sessions = examination.exam_sessions.all()
        serializer = ExaminationSessionSerializer(sessions, many=True)
        return Response(serializer.data)

    @action(detail=True, methods=['get'])
    def statistics(self, request, pk=None):
        """获取考试统计信息"""
        examination = self.get_object()

        # 权限检查
        if (examination.creator != request.user and
            not request.user.is_admin_user and
            not examination.supervisors.filter(id=request.user.id).exists()):
            return Response(
                {'error': '没有权限查看统计信息'},
                status=status.HTTP_403_FORBIDDEN
            )

        # 获取或创建统计对象
        statistics, created = ExamStatistics.objects.get_or_create(examination=examination)

        # 更新统计数据
        statistics.update_statistics()
        statistics.refresh_from_db()

        serializer = ExamStatisticsSerializer(statistics)
        return Response(serializer.data)

    @action(detail=True, methods=['get'])
    def export_results(self, request, pk=None):
        """导出考试结果"""
        examination = self.get_object()

        # 权限检查
        if (examination.creator != request.user and
            not request.user.is_admin_user and
            not examination.supervisors.filter(id=request.user.id).exists()):
            return Response(
                {'error': '没有权限导出考试结果'},
                status=status.HTTP_403_FORBIDDEN
            )

        # 获取完成的考试会话
        sessions = examination.exam_sessions.filter(status='completed').select_related('user')

        # 创建CSV内容
        output = io.StringIO()
        writer = csv.writer(output)

        # 写入表头
        headers = [
            '用户名', '真实姓名', '开始时间', '结束时间', '用时(秒)',
            '总分', '客观题分数', '主观题分数', '是否通过'
        ]
        writer.writerow(headers)

        # 写入数据
        for session in sessions:
            row = [
                session.user.username,
                session.user.real_name,
                session.started_at.strftime('%Y-%m-%d %H:%M:%S') if session.started_at else '',
                session.finished_at.strftime('%Y-%m-%d %H:%M:%S') if session.finished_at else '',
                session.time_spent,
                session.total_score or 0,
                session.objective_score or 0,
                session.subjective_score or 0,
                '是' if session.passed else '否'
            ]
            writer.writerow(row)

        # 生成HTTP响应
        response = HttpResponse(
            output.getvalue(),
            content_type='text/csv; charset=utf-8-sig'
        )
        response['Content-Disposition'] = f'attachment; filename="{examination.title}_考试结果.csv"'

        return response

    @action(detail=True, methods=['post'])
    def add_questions(self, request, pk=None):
        """添加考试题目"""
        examination = self.get_object()

        # 权限检查
        if examination.creator != request.user and not request.user.is_admin_user:
            return Response(
                {'error': '没有权限操作此考试'},
                status=status.HTTP_403_FORBIDDEN
            )

        if examination.status != Examination.ExamStatus.DRAFT:
            return Response(
                {'error': '只有草稿状态的考试才能添加题目'},
                status=status.HTTP_400_BAD_REQUEST
            )

        question_ids = request.data.get('question_ids', [])
        if not question_ids:
            return Response(
                {'error': '请提供要添加的题目ID列表'},
                status=status.HTTP_400_BAD_REQUEST
            )

        from apps.question_bank.models import Question
        questions = Question.objects.filter(id__in=question_ids)

        added_count = 0
        for question in questions:
            # 检查是否已存在
            if not examination.questions.filter(question=question).exists():
                # 获取最大排序号
                max_order = examination.questions.aggregate(
                    max_order=Count('question')
                )['max_order'] or 0

                ExaminationQuestion.objects.create(
                    examination=examination,
                    question=question,
                    question_order=max_order + 1
                )
                added_count += 1

        # 更新总分
        total_score = sum(q.effective_score for q in examination.questions.all())
        examination.total_score = total_score
        examination.save(update_fields=['total_score'])

        return Response({
            'success': True,
            'data': {
                'added_count': added_count,
                'total_questions': examination.questions.count(),
                'total_score': float(total_score)
            }
        })

    @action(detail=True, methods=['post'])
    def remove_questions(self, request, pk=None):
        """删除考试题目"""
        examination = self.get_object()

        # 权限检查
        if examination.creator != request.user and not request.user.is_admin_user:
            return Response(
                {'error': '没有权限操作此考试'},
                status=status.HTTP_403_FORBIDDEN
            )

        if examination.status != Examination.ExamStatus.DRAFT:
            return Response(
                {'error': '只有草稿状态的考试才能删除题目'},
                status=status.HTTP_400_BAD_REQUEST
            )

        question_ids = request.data.get('question_ids', [])
        if not question_ids:
            return Response(
                {'error': '请提供要删除的题目ID列表'},
                status=status.HTTP_400_BAD_REQUEST
            )

        deleted_count = examination.questions.filter(question_id__in=question_ids).delete()[0]

        # 更新总分和排序
        total_score = sum(q.effective_score for q in examination.questions.all())
        examination.total_score = total_score
        examination.save(update_fields=['total_score'])

        # 重新排序
        for i, exam_question in enumerate(examination.questions.all(), 1):
            exam_question.question_order = i
            exam_question.save(update_fields=['question_order'])

        return Response({
            'success': True,
            'data': {
                'removed_count': deleted_count,
                'total_questions': examination.questions.count(),
                'total_score': float(total_score)
            }
        })

    @action(detail=True, methods=['post'])
    def reorder_questions(self, request, pk=None):
        """重新排序考试题目"""
        examination = self.get_object()

        # 权限检查
        if examination.creator != request.user and not request.user.is_admin_user:
            return Response(
                {'error': '没有权限操作此考试'},
                status=status.HTTP_403_FORBIDDEN
            )

        if examination.status != Examination.ExamStatus.DRAFT:
            return Response(
                {'error': '只有草稿状态的考试才能重新排序题目'},
                status=status.HTTP_400_BAD_REQUEST
            )

        question_orders = request.data.get('question_orders', {})
        if not question_orders:
            return Response(
                {'error': '请提供排序信息'},
                status=status.HTTP_400_BAD_REQUEST
            )

        updated_count = 0
        for question_id, order in question_orders.items():
            try:
                exam_question = examination.questions.get(question_id=question_id)
                exam_question.question_order = order
                exam_question.save(update_fields=['question_order'])
                updated_count += 1
            except ExaminationQuestion.DoesNotExist:
                continue

        return Response({
            'success': True,
            'data': {'updated_count': updated_count}
        })


class ExaminationSessionViewSet(viewsets.ModelViewSet):
    """考试会话ViewSet"""
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        """根据用户权限获取考试会话"""
        user = self.request.user

        if user.is_admin_user:
            return ExaminationSession.objects.all()
        elif user.is_teacher:
            # 教师可以查看自己创建的和监考的考试会话
            return ExaminationSession.objects.filter(
                Q(examination__creator=user) | Q(examination__supervisors=user)
            ).distinct()
        else:
            # 学生只能查看自己的考试会话
            return ExaminationSession.objects.filter(user=user)

    def get_serializer_class(self):
        """根据操作类型获取序列化器"""
        if self.action == 'retrieve':
            return ExaminationSessionDetailSerializer
        return ExaminationSessionSerializer

    @action(detail=False, methods=['post'])
    def join_exam(self, request):
        """加入考试"""
        examination_id = request.data.get('examination_id')
        if not examination_id:
            return Response(
                {'error': '请提供考试ID'},
                status=status.HTTP_400_BAD_REQUEST
            )

        examination = get_object_or_404(Examination, id=examination_id)

        # 检查是否可以参与考试
        can_participate, message = examination.can_participate(request.user)
        if not can_participate:
            return Response(
                {'error': message},
                status=status.HTTP_400_BAD_REQUEST
            )

        now = timezone.now()
        if now < examination.start_time:
            return Response(
                {'error': '考试尚未开始'},
                status=status.HTTP_400_BAD_REQUEST
            )

        if now > examination.end_time:
            return Response(
                {'error': '考试已结束'},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 创建考试会话
        session, created = ExaminationSession.objects.get_or_create(
            examination=examination,
            user=request.user,
            defaults={
                'status': ExaminationSession.SessionStatus.JOINED,
                'ip_address': request.META.get('REMOTE_ADDR'),
                'user_agent': request.META.get('HTTP_USER_AGENT', '')[:500]
            }
        )

        if not created and not examination.allow_retake:
            return Response(
                {'error': '不允许重复参加考试'},
                status=status.HTTP_400_BAD_REQUEST
            )

        return Response({
            'success': True,
            'data': {
                'session_id': str(session.id),
                'examination_title': examination.title,
                'duration': examination.duration,
                'start_time': examination.start_time,
                'end_time': examination.end_time,
                'show_score': examination.show_score,
                'show_answer': examination.show_answer
            }
        })

    @action(detail=True, methods=['post'])
    def start_exam(self, request, pk=None):
        """开始答题"""
        session = self.get_object()

        # 权限检查
        if session.user != request.user:
            return Response(
                {'error': '没有权限操作此考试会话'},
                status=status.HTTP_403_FORBIDDEN
            )

        if session.status != ExaminationSession.SessionStatus.JOINED:
            return Response(
                {'error': '只能从已加入状态开始答题'},
                status=status.HTTP_400_BAD_REQUEST
            )

        now = timezone.now()
        if now < session.examination.start_time:
            return Response(
                {'error': '考试尚未开始'},
                status=status.HTTP_400_BAD_REQUEST
            )

        if now > session.examination.end_time:
            return Response(
                {'error': '考试已结束'},
                status=status.HTTP_400_BAD_REQUEST
            )

        session.status = ExaminationSession.SessionStatus.IN_PROGRESS
        session.started_at = now
        session.save(update_fields=['status', 'started_at'])

        # 获取考试题目
        questions = session.examination.questions.all().order_by('question_order')

        return Response({
            'success': True,
            'data': {
                'session_id': str(session.id),
                'started_at': session.started_at,
                'duration': session.examination.duration,
                'questions': [
                    {
                        'id': str(eq.id),
                        'question_id': str(eq.question.id),
                        'title': eq.question.title,
                        'type': eq.question.type,
                        'content': eq.question.stem,
                        'options': eq.question.options,
                        'order': eq.question_order,
                        'score': float(eq.effective_score),
                        'is_required': eq.is_required
                    }
                    for eq in questions
                ]
            }
        })

    @action(detail=True, methods=['post'])
    def submit_answer(self, request, pk=None):
        """提交答案"""
        session = self.get_object()

        # 权限检查
        if session.user != request.user:
            return Response(
                {'error': '没有权限操作此考试会话'},
                status=status.HTTP_403_FORBIDDEN
            )

        if session.status != ExaminationSession.SessionStatus.IN_PROGRESS:
            return Response(
                {'error': '只能在进行中的考试提交答案'},
                status=status.HTTP_400_BAD_REQUEST
            )

        exam_question_id = request.data.get('exam_question_id')
        answer_data = request.data.get('answer')
        text_answer = request.data.get('text_answer', '')

        if not exam_question_id:
            return Response(
                {'error': '请提供考试题目ID'},
                status=status.HTTP_400_BAD_REQUEST
            )

        try:
            exam_question = ExaminationQuestion.objects.get(id=exam_question_id)
        except ExaminationQuestion.DoesNotExist:
            return Response(
                {'error': '考试题目不存在'},
                status=status.HTTP_404_NOT_FOUND
            )

        if exam_question.examination != session.examination:
            return Response(
                {'error': '题目不属于此考试'},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 创建或更新答案
        serializer = ExaminationAnswerCreateSerializer(data={
            'exam_session': session.id,
            'exam_question': exam_question.id,
            'answer': answer_data,
            'text_answer': text_answer,
            'answered_at': timezone.now()
        })

        if serializer.is_valid():
            answer = serializer.save()

            # 自动评分客观题
            if exam_question.question.type in ['choice', 'multiple_choice', 'true_false']:
                answer.auto_grade()

            return Response({
                'success': True,
                'data': {
                    'answer_id': str(answer.id),
                    'score': float(answer.score) if answer.score else None,
                    'is_correct': answer.is_correct
                }
            })
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    @action(detail=True, methods=['post'])
    def submit_exam(self, request, pk=None):
        """提交考试"""
        session = self.get_object()

        # 权限检查
        if session.user != request.user:
            return Response(
                {'error': '没有权限操作此考试会话'},
                status=status.HTTP_403_FORBIDDEN
            )

        if session.status != ExaminationSession.SessionStatus.IN_PROGRESS:
            return Response(
                {'error': '只能提交进行中的考试'},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 计算用时
        if session.started_at:
            session.time_spent = int((timezone.now() - session.started_at).total_seconds())

        # 计算总分
        total_score = session.calculate_score()

        session.status = ExaminationSession.SessionStatus.SUBMITTED
        session.finished_at = timezone.now()
        session.save(update_fields=['status', 'finished_at', 'time_spent', 'total_score', 'passed'])

        return Response({
            'success': True,
            'data': {
                'total_score': float(total_score),
                'passed': session.passed,
                'time_spent': session.time_spent,
                'finished_at': session.finished_at
            }
        })

    @action(detail=True, methods=['get'])
    def get_remaining_time(self, request, pk=None):
        """获取剩余时间"""
        session = self.get_object()

        # 权限检查
        if session.user != request.user:
            return Response(
                {'error': '没有权限查看此考试会话信息'},
                status=status.HTTP_403_FORBIDDEN
            )

        if session.status != ExaminationSession.SessionStatus.IN_PROGRESS:
            return Response({
                'remaining_time': 0,
                'status': session.status
            })

        remaining_time = session.remaining_time

        return Response({
            'remaining_time': remaining_time,
            'status': session.status
        })


class ExaminationAnswerViewSet(viewsets.ModelViewSet):
    """考试答案ViewSet"""
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        """根据用户权限获取答案"""
        user = self.request.user

        if user.is_admin_user:
            return ExaminationAnswer.objects.all()
        elif user.is_teacher:
            # 教师可以查看自己创建的考试和监考考试的答案
            return ExaminationAnswer.objects.filter(
                Q(exam_session__examination__creator=user) |
                Q(exam_session__examination__supervisors=user)
            ).distinct()
        else:
            # 学生只能查看自己的答案
            return ExaminationAnswer.objects.filter(exam_session__user=user)

    def get_serializer_class(self):
        """根据操作类型获取序列化器"""
        if self.action == 'retrieve':
            return SessionAnswerDetailSerializer
        return ExaminationAnswerSerializer

    def get_permissions(self):
        """根据操作类型获取权限"""
        if self.action in ['create', 'update', 'partial_update']:
            # 答题权限需要是考生本人
            return [IsAuthenticated]
        return super().get_permissions()

    @action(detail=False, methods=['post'])
    def batch_grade(self, request):
        """批量评分主观题"""
        if not request.user.is_teacher and not request.user.is_admin_user:
            return Response(
                {'error': '没有评分权限'},
                status=status.HTTP_403_FORBIDDEN
            )

        answer_ids = request.data.get('answer_ids', [])
        if not answer_ids:
            return Response(
                {'error': '请提供要评分的答案ID列表'},
                status=status.HTTP_400_BAD_REQUEST
            )

        scores = request.data.get('scores', {})
        if not scores:
            return Response(
                {'error': '请提供评分信息'},
                status=status.HTTP_400_BAD_REQUEST
            )

        updated_count = 0
        for answer_id in answer_ids:
            try:
                answer = ExaminationAnswer.objects.get(id=answer_id)
                question = answer.exam_question.question

                # 只评分主观题
                if question.type in ['choice', 'multiple_choice', 'true_false']:
                    continue

                score = scores.get(str(answer_id))
                if score is not None:
                    answer.score = score
                    answer.status = ExaminationAnswer.AnswerStatus.MANUALLY_GRADED
                    answer.save(update_fields=['score', 'status'])
                    updated_count += 1

            except ExaminationAnswer.DoesNotExist:
                continue

        return Response({
            'success': True,
            'data': {'updated_count': updated_count}
        })


class ExaminationTemplateViewSet(viewsets.ModelViewSet):
    """考试模板ViewSet"""
    permission_classes = [IsAuthenticated]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['exam_type']

    def get_queryset(self):
        """根据用户权限获取模板"""
        user = self.request.user

        if user.is_admin_user:
            return ExaminationTemplate.objects.all()
        else:
            # 教师只能查看自己创建的模板
            return ExaminationTemplate.objects.filter(creator=user)

    def get_serializer_class(self):
        """根据操作类型获取序列化器"""
        return ExaminationTemplateSerializer

    def perform_create(self, serializer):
        """创建模板时设置创建者"""
        serializer.save(creator=self.request.user)

    def get_permissions(self):
        """根据操作类型获取权限"""
        if self.action in ['create', 'update', 'partial_update', 'destroy']:
            # 模板管理需要教师或管理员权限
            from common.permissions import IsTeacherOrAdmin
            return [IsAuthenticated, IsTeacherOrAdmin]
        return super().get_permissions()

    @action(detail=True, methods=['post'])
    def create_exam_from_template(self, request, pk=None):
        """从模板创建考试"""
        template = self.get_object()

        # 权限检查
        if template.creator != request.user and not request.user.is_admin_user:
            return Response(
                {'error': '没有权限使用此模板'},
                status=status.HTTP_403_FORBIDDEN
            )

        # 增加使用次数
        template.usage_count += 1
        template.save(update_fields=['usage_count'])

        # 创建考试数据
        exam_data = {
            'title': f"基于模板-{template.name}-{timezone.now().strftime('%Y%m%d%H%M%S')}",
            'description': template.description,
            'exam_type': template.exam_type,
            'duration': template.duration,
            'question_mode': template.question_mode,
            'total_score': template.total_score,
            'pass_score': template.get_pass_score(),
            'settings': template.settings,
            'question_bank_id': request.data.get('question_bank_id')
        }

        # 合并考试设置
        exam_data.update(template.settings)

        # 这里简化处理，实际应该调用创建考试的逻辑
        return Response({
            'success': True,
            'data': exam_data
        })


class QuestionBankSelectViewSet(viewsets.ReadOnlyModelViewSet):
    """题库选择ViewSet（用于考试创建）"""
    permission_classes = [IsAuthenticated]
    serializer_class = QuestionBankSelectSerializer

    def get_queryset(self):
        """根据用户权限获取题库"""
        user = self.request.user

        if user.is_admin_user:
            from apps.question_bank.models import QuestionBank
            return QuestionBank.objects.all()
        elif user.is_teacher:
            from apps.question_bank.models import QuestionBank
            return QuestionBank.objects.filter(
                Q(owner=user) | Q(is_public=True)
            ).distinct()
        else:
            # 学生不访问题库选择
            from apps.question_bank.models import QuestionBank
            return QuestionBank.objects.none()

    @action(detail=True, methods=['get'])
    def questions(self, request, pk=None):
        """获取题库中的题目"""
        question_bank = self.get_object()

        # 权限检查
        if not question_bank.can_access(request.user):
            return Response(
                {'error': '没有权限访问题库'},
                status=status.HTTP_403_FORBIDDEN
            )

        from apps.question_bank.models import QuestionBankItem
        items = question_bank.question_items.select_related('question').filter(status='active')

        # 过滤参数
        question_type = request.query_params.get('type')
        difficulty = request.query_params.get('difficulty')
        subject = request.query_params.get('subject')

        if question_type:
            items = items.filter(question__type=question_type)
        if difficulty:
            items = items.filter(question__difficulty=difficulty)
        if subject:
            items = items.filter(question__subject=subject)

        questions = [item.question for item in items]
        serializer = QuestionListSerializer(questions, many=True)

        return Response(serializer.data)